package io.renren.controller;

import io.renren.annotation.Login;
import io.renren.annotation.LoginUser;
import io.renren.cloud.OSSFactory;
import io.renren.common.exception.RRException;
import io.renren.common.utils.DateUtils;
import io.renren.common.utils.ProjectConstant;
import io.renren.common.utils.R;
import io.renren.common.validator.Assert;
import io.renren.entity.MemberEntity;
import io.renren.entity.SysOssEntity;
import io.renren.form.PayInfoForm;
import io.renren.service.MemberService;
import io.renren.service.SysOssService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import java.io.ByteArrayOutputStream;
import java.util.Date;
import java.util.UUID;

import net.coobird.thumbnailator.Thumbnails;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import springfox.documentation.annotations.ApiIgnore;

/**
 * 会员接口
 *
 * @author chenshun
 * @email sunlightcs@gmail.com
 * @date 2017-03-23 15:31
 */
@RestController
@RequestMapping("/api/member")
@Api(tags = "会员接口")
public class ApiMemberController extends AbstractController {

	@Autowired
	private MemberService memberService;

	@Autowired
	private SysOssService sysOssService;

	@Login
	@PostMapping("info")
	@ApiOperation("获取会员信息")
	public R info(@ApiIgnore @LoginUser MemberEntity member) {
		return R.ok().put("member", member);
	}

	@Login
	@PostMapping("setPay")
	@ApiOperation("设置收款信息")
	public R setPay(@ApiIgnore @LoginUser MemberEntity member, @RequestBody PayInfoForm form) {
		if (StringUtils.isNotBlank(form.getBankName())) {

			Assert.isNull(member.getBankCardNumber(), "禁止修改信息");

			Assert.hasText(form.getRealname(), "真实姓名不能为空");
			Assert.hasText(form.getBankCardNumber(), "银行卡号不能为空");
			Assert.hasText(form.getBankName(), "银行名称不能为空");

			member.setBankName(form.getBankName());
			member.setBankNameBranch(form.getBankNameBranch());
			member.setBankCardNumber(form.getBankCardNumber());

			member.setRealname(form.getRealname());
		} else if (StringUtils.isNotBlank(form.getAlipay())) {

			Assert.isNull(member.getAlipay(), "禁止修改信息");
			Assert.hasText(member.getAlipayImg(), "请上传支付宝收款码");

			member.setAlipay(form.getAlipay());
		} else if (StringUtils.isNotBlank(form.getWechat())) {

			Assert.isNull(member.getWechat(), "禁止修改信息");
			Assert.hasText(member.getWechatImg(), "请上传微信收款码");

			member.setWechat(form.getWechat());
		} else {
			throw new RRException("设置收款信息失败");
		}
		member.setUpdateTime(new Date());
		memberService.updateById(member);
		return R.ok();
	}

	@Login
	@PostMapping("/upload/alipay")
	@ApiOperation("支付宝收款码")
	public R uploadAlipay(@RequestParam("file") MultipartFile file) {
		String url = uploadFile(file, ProjectConstant.UPLOAD_TYPE_ALIPAY);
		memberService.updateImage(getUserId(), ProjectConstant.UPLOAD_TYPE_ALIPAY, url);
		return R.ok();
	}

	@Login
	@PostMapping("/upload/wechat")
	@ApiOperation("微信收款码")
	public R uploadWechat(@RequestParam("file") MultipartFile file) {
		String url = uploadFile(file, ProjectConstant.UPLOAD_TYPE_WECHAT);
		memberService.updateImage(getUserId(), ProjectConstant.UPLOAD_TYPE_WECHAT, url);
		return R.ok();
	}

	/**
	 * 上传文件
	 * 
	 * @param file
	 * @param type
	 */
	private String uploadFile(MultipartFile file, int type) {
		if (file == null || file.isEmpty()) {
			throw new RRException("上传文件不能为空");
		}
		// 上传文件
		String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
		Assert.isImage(suffix, "请上传图片文件");
		try {
			// 生成文件名
			String fileName = UUID.randomUUID().toString().replaceAll("-", "") + suffix;
			// 文件路径
			String path = "pay/" + DateUtils.format(new Date(), "yyyyMMdd") + "/";
			// 压缩图片
			ByteArrayOutputStream bos = new ByteArrayOutputStream();
			Thumbnails.of(file.getInputStream()).scale(0.75f).outputQuality(0.75f).toOutputStream(bos);
			String url = OSSFactory.build().upload(bos.toByteArray(), path + fileName);
			// 保存文件信息
			SysOssEntity ossEntity = new SysOssEntity();
			ossEntity.setUrl(url);
			ossEntity.setCreateDate(new Date());
			sysOssService.insert(ossEntity);
			return url;
		} catch (Exception e) {
			logger.error("上传文件失败", e);
			throw new RRException("上传文件失败");
		}
	}
}
